package com.tourlaid.mamagerment.service.impl

import com.tourlaid.mamagerment.dto.CommentDto
import com.tourlaid.mamagerment.dto.MyCommentDto
import com.tourlaid.mamagerment.entity.Comment
import com.tourlaid.mamagerment.enums.TldExceptionEnum
import com.tourlaid.mamagerment.mapper.CommentMapper
import com.tourlaid.mamagerment.service.CommentService
import com.tourlaid.mamagerment.util.LoginUtil
import com.tourlaid.mamagerment.util.TldException
import org.springframework.stereotype.Service
import org.springframework.util.StringUtils
import java.util.*
import javax.annotation.Resource

/**
 * Created by xiaoyongge on 2017/8/12.
 */
@Service("commentService")
class CommentServiceImpl : CommentService {

    @Resource
    val commentMapper: CommentMapper? = null

    override fun queryOtherCByThoughtId(toUserId: Long, thoughtId: Long): List<CommentDto> {
        return commentMapper!!.queryOtherCByThoughtId(toUserId, thoughtId)
    }

    override fun queryWeCByThoughtId(fromUserId: Long, toUserId: Long, thoughtId: Long): List<Comment> {
        return commentMapper!!.queryWeCByThoughtId(fromUserId, toUserId, thoughtId)
    }

    override fun publicComment(fromUserId: Long?, toUserId: Long?, thoughtId: Long?, content: String?) {
        toUserId ?: throw TldException(TldExceptionEnum.TOUSERID_NULL)
        thoughtId ?: throw TldException(TldExceptionEnum.THOUGHTID_NULL)
        if (StringUtils.isEmpty(content)) throw TldException(TldExceptionEnum.COMMENT_NULL)
        if (content!!.length > 22) throw TldException(TldExceptionEnum.COMMENT_TOO_LONG)
        var comment = Comment()
        comment.fromUserId = fromUserId
        comment.toUserId = toUserId
        comment.thoughtId = thoughtId
        comment.content = content
        comment.creator = fromUserId
        comment.editor = fromUserId
        commentMapper!!.insert(comment)
    }

    /**
     * 主人能删全部的
     * 客人只能删自己的
     */
    override fun deleteComment(thoughtId: Long, ownUserId: Long, id: Long) {
        var comment = this.getById(id)
        if (!Objects.equals(thoughtId, comment.thoughtId)) throw TldException(TldExceptionEnum.OTHER_THOUGHT)
        if (!Objects.equals(ownUserId, LoginUtil.userId)) {
            if (!Objects.equals(comment.fromUserId, LoginUtil.userId)) throw TldException(TldExceptionEnum.OTHER_COMMENT)
        }
        commentMapper!!.delete(id, LoginUtil.userId)
    }

    override fun getById(id: Long): Comment {
        return commentMapper!!.getById(id)
    }

    override fun queryByToUserId(userId: Long): List<MyCommentDto> {
        return commentMapper!!.queryByToUserId(userId)
    }

    override fun queryByFromUserId(fromUserId: Long): List<MyCommentDto> {
        return commentMapper!!.queryByFromUserId(fromUserId)
    }

    override fun queryByThoughtId(thoughtId: Long): List<Comment> {
        return commentMapper!!.queryByThoughtId(thoughtId)
    }
}